import React, { useState } from 'react';
import { DownOutlined, PlusOutlined, CloseOutlined, LoadingOutlined } from '@ant-design/icons';
import API from '../../api/client';

const ERModelConfigModal = ({ 
  visible, 
  onClose, 
  dataSourceId
  // refreshErModels
}) => {
  const [configType, setConfigType] = useState('er_file');
  const [erFile, setErFile] = useState(null);
  const [tableName, setTableName] = useState('');
  const [scope, setScope] = useState('local');
  const [previewContent, setPreviewContent] = useState('');
  const [isSaving, setIsSaving] = useState(false);

  const handleConfigTypeChange = (e) => {
    setConfigType(e.target.value);
    setPreviewContent('');
  };

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    
    const validTypes = ['application/json', 'text/x-sql', 'application/xml'];
    const validExtensions = ['.json', '.sql', '.xml'];
    
    if (
      !validTypes.includes(file.type) && 
      !validExtensions.some(ext => file.name.endsWith(ext))
    ) {
      alert('请上传JSON、SQL或XML格式的文件');
      return;
    }
    
    setErFile(file);
    
    // 读取文件内容进行预览
    const reader = new FileReader();
    reader.onload = (e) => {
      const content = e.target.result;
      setPreviewContent(content);
    };
    reader.readAsText(file);
  }; 

  const handleSave = async () => {
    // 根据配置类型生成模型名称
    let modelName = '';
    
    if (configType === 'er_file') {
      if (!erFile) {
        alert('请上传ER文件');
        return;
      }
      
      // 获取文件名（不包含扩展名）作为模型名称
      const fileName = erFile.name;
      const dotIndex = fileName.lastIndexOf('.');
      modelName = dotIndex !== -1 ? fileName.substring(0, dotIndex) : fileName;
    } else {
      if (!tableName.trim()) {
        alert('请填写表名');
        return;
      }
      
      // 使用输入的表名作为模型名称
      modelName = tableName.trim();
    }
    
    setIsSaving(true);
    
    try {
      // 准备基本数据 - 使用自动生成的模型名称
      const erModelData = {
        source_id: dataSourceId,
        name: modelName,
        config_type: configType,
        scope: scope
      };
  
      // 处理ER文件类型
      if (configType === 'er_file') {
        // 添加content字段
        erModelData.content = previewContent; // 关键修复
        erModelData.file_name = erFile.name;
      } 
      // 处理表名类型
      else {
        erModelData.table_name = tableName;
      }
      
      // 调用API创建ER模型
      await API.createERModel(erModelData);
      
      // 刷新ER模型列表
      // refreshErModels();
      
      // 关闭模态框
      onClose();
      
      alert('ER模型创建成功！');
    } catch (error) {
      console.error('创建ER模型失败:', error);
      alert(`创建ER模型失败: ${error.message || '请检查网络连接后重试'}`);
    } finally {
      setIsSaving(false);
    }
  };

  if (!visible) return null;

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '600px' }}>
        <div className="modal-header">
          <h3 style={{ fontSize: '20px', fontWeight: 600, color: '#1890ff' }}>
            配置ER模型
          </h3>
          <button className="close-btn" onClick={onClose} aria-label="关闭">
            <CloseOutlined style={{ fontSize: '18px' }} />
          </button>
        </div>
        
        <div className="modal-body">
          <div className="form-group" style={{ marginBottom: '20px' }}>
            <label style={{ display: 'block', marginBottom: '8px', fontWeight: 500 }}>
              配置类型
            </label>
            <div className="custom-select">
              <select 
                value={configType} 
                onChange={handleConfigTypeChange}
                className="form-control"
              >
                <option value="er_file">ER文件</option>
                <option value="table_name">表名</option>
              </select>
              <DownOutlined className="select-arrow" />
            </div>
          </div>
          
          {configType === 'er_file' ? (
            <div className="upload-options">
              <label className="upload-btn">
                <input 
                  type="file" 
                  accept=".json,.sql,.xml" 
                  onChange={handleFileChange}
                  style={{ display: 'none' }}
                />
                <div style={{
                  width: '60px',
                  height: '60px',
                  borderRadius: '50%',
                  background: '#e6f7ff',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  marginBottom: '15px',
                  border: '2px dashed #91d5ff',
                  cursor: 'pointer'
                }}>
                  <PlusOutlined style={{ fontSize: '32px', color: '#1890ff' }} />
                </div>
                <span style={{ fontSize: '16px', fontWeight: 500 }}>点击上传ER文件</span>
                <p className="upload-hint">
                  支持 .json, .sql, .xml 格式
                </p>
                {erFile && (
                  <div style={{
                    marginTop: '15px',
                    color: '#1890ff',
                    fontWeight: 500,
                    fontSize: '14px'
                  }}>
                    已选择: {erFile.name}
                    <p style={{ color: '#666', marginTop: '5px', fontSize: '12px' }}>
                      模型名称将自动设置为: {
                        erFile.name.includes('.') 
                          ? erFile.name.substring(0, erFile.name.lastIndexOf('.'))
                          : erFile.name
                      }
                    </p>
                  </div>
                )}
              </label>
            </div>
          ) : (
            <div>
              <div className="form-group">
                <label style={{ display: 'block', marginBottom: '8px', fontWeight: 500 }}>
                  表名 (逗号分隔)
                </label>
                <input
                  type="text"
                  value={tableName}
                  onChange={(e) => setTableName(e.target.value)}
                  className="form-control"
                  placeholder="例如: users,orders,products"
                  required
                />
                <p style={{ color: '#666', marginTop: '5px', fontSize: '12px' }}>
                  模型名称将自动设置为: {tableName.trim() || '[您输入的表名]'}
                </p>
              </div>
              
              {/* 范围选择器 */}
              <div className="form-group">
                <label style={{ display: 'block', marginBottom: '8px', fontWeight: 500 }}>
                  探查范围
                </label>
                <div className="scope-options">
                  <label className="scope-option" style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
                    <input
                      type="radio"
                      name="scope"
                      value="local"
                      checked={scope === 'local'}
                      onChange={() => setScope('local')}
                      style={{ marginRight: '8px' }}
                    />
                    <div>
                      <span className="scope-label" style={{ fontWeight: 500 }}>局部探查</span>
                      <div className="scope-hint" style={{ fontSize: '12px', color: '#666' }}>仅探查提供的表</div>
                    </div>
                  </label>
                  
                  <label className="scope-option" style={{ display: 'flex', alignItems: 'center' }}>
                    <input
                      type="radio"
                      name="scope"
                      value="global"
                      checked={scope === 'global'}
                      onChange={() => setScope('global')}
                      style={{ marginRight: '8px' }}
                    />
                    <div>
                      <span className="scope-label" style={{ fontWeight: 500 }}>全局探查</span>
                      <div className="scope-hint" style={{ fontSize: '12px', color: '#666' }}>探查提供的表及其关联表</div>
                    </div>
                  </label>
                </div>
              </div>
            </div>
          )}
          
          {previewContent && (
            <div className="er-preview">
              <h4 style={{ fontSize: '16px', fontWeight: 600, marginBottom: '15px' }}>
                预览
              </h4>
              <div className="preview-content" style={{ 
                background: '#f8f8f8', 
                padding: '15px', 
                borderRadius: '6px', 
                maxHeight: '250px', 
                overflow: 'auto',
                fontFamily: "'Courier New', monospace",
                whiteSpace: 'pre-wrap',
                border: '1px solid #e8e8e8',
                boxShadow: 'inset 0 1px 3px rgba(0,0,0,0.1)',
                fontSize: '13px',
                lineHeight: '1.5'
              }}>
                {previewContent}
              </div>
            </div>
          )}
        </div>
        
        <div className="modal-footer">
          <button className="btn-outline" onClick={onClose} disabled={isSaving}>
            取消
          </button>
          <button 
            className="btn-primary" 
            onClick={handleSave} 
            disabled={isSaving}
          >
            {isSaving ? (
              <>
                <LoadingOutlined style={{ marginRight: 8 }} /> 
                保存中...
              </>
            ) : '保存配置'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default ERModelConfigModal;